using System;
using System.Diagnostics;
using System.IO;
using System.Collections.Generic;

namespace CoverageRunner
{
    public class VisualStudioInstrumentation
    {
        private readonly string vsinstr;

        public VisualStudioInstrumentation(string vsinstrLocation)
        {
            vsinstr = Path.Combine(vsinstrLocation, "vsinstr.exe");

            if (!File.Exists(vsinstr))
                throw new ApplicationException(string.Format("The specified path '{0}' to VSINSTR.EXE did not contain the application", vsinstrLocation));
        }

        public void Instrument(string outputPath, List<string> targetsToInstrument)
        {
            if (targetsToInstrument.Count==0)
                throw new ApplicationException("No targets were specified to instrument");

            foreach (string target in targetsToInstrument)
            {
                string arguments = string.Format("/COVERAGE \"{0}\" /OUTPUTPATH:\"{1}\"", target, outputPath);

                Process p = new Process();
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.FileName = vsinstr;
                p.StartInfo.Arguments = arguments;
                p.Start();
                p.WaitForExit();

                if (p.ExitCode!=0) throw new ApplicationException("Unable to successfully instrument targets");
            }
        }
    }
}